package com.chandon.juc.thread_communication.AlternatePrinting;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 2个线程交替打印A与B，重复n次
 *
 * @author Dong
 */

public class UseCondition {

	static ReentrantLock reentrantLock = new ReentrantLock();

	static Condition conditionA = reentrantLock.newCondition();
	static Condition conditionB = reentrantLock.newCondition();


	public static void test() {



		Thread threadA = new Thread(() -> {


			try {
				reentrantLock.lock();
				for (int i = 0; i < 50; i++) {

					System.out.println("A:" + i);
					conditionB.signal();
					conditionA.await();
				}
				reentrantLock.unlock();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}


		});


		Thread threadB = new Thread(() -> {


			try {
				reentrantLock.lock();
				for (int i = 0; i < 50; i++) {

					conditionB.await();
					System.out.println("B:" + i);
					conditionA.signal();

				}
				reentrantLock.unlock();

			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
		});

		threadA.start();
		threadB.start();


	}


	public static void test2(){


	}

	public static void main(String[] args) throws InterruptedException {


		for (int i = 0; i < 10; i++) {

			test();
			Thread.sleep(2000);
		}
	}

}
